//
//  MoreViewController.m
//  SYiDaiy
//
//  Created by dllo on 16/8/29.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "MoreViewController.h"
#import "TAMacro.h"
#import "AFNetworking.h"
#import "MoreESRootClass.h"
#import "MoreGrids.h"
#import "MoreGoodies.h"
#import "MoreVersion.h"
#import "MoreBanner_Brand.h"
#import "MoreBadge.h"
#import "MoreApps.h"



#import "MoreDetailViewController.h"
#import "moreMiddleViewController.h"

#import "BrandTopViewController.h"
#import "MoreCustomTableViewCell.h"
#import "MoreCollectionViewController.h"
#import "MoreMiddleViewController.h"
#import "CustomView.h"
#import "UIView+Frame.h"
#import "MoreView.h"
#import "CollectionButtonViewController.h"
#import "SetViewController.h"
#import "Masonry.h"

@interface MoreViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) MoreView *moreView;
@property (nonatomic,strong) UIView *morebackView;

@property (nonatomic,strong) UITableView *moreTableView;
@property (nonatomic,strong) CustomView *headerView;

@property (nonatomic,strong) MoreESRootClass *moreESRootClass;
@property (nonatomic,copy) NSString *strOfCache;

@property (nonatomic,strong) UILabel *proLabel;
@end

@implementation MoreViewController
#pragma mark -----more试图加载
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createNavigationItem];
    [self.moreTableView reloadData];
    [self moreNetworkGet];
    
    [self createTableView];
}
    
    
    
    
   
    
    
    
    
    
    
   


- (void)createmoreView
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewDisappear)];

    _moreView = [[MoreView alloc] initWithFrame:CGRectMake(0, 667, SCREEN_WIDTH, 500)];
    _moreView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_moreView];
    
    _morebackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 375, 167)];
    [_morebackView addGestureRecognizer:tap];
    [self.view addSubview:_morebackView];
    
    [_moreView.appstoreButton addTarget:self action:@selector(viewDisappear) forControlEvents:UIControlEventTouchUpInside];
}

- (void)createNavigationItem
{
    self.navigationItem.title = @"WATCHMORE";
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ButtonLove"] style:UIBarButtonItemStyleDone target:self action:@selector(viewAppear)];
}

//创建tableview
- (void)createTableView
{
    _moreTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 49 - 64) style:UITableViewStylePlain];
    _moreTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _headerView = [[CustomView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
    _headerView.backgroundColor = [UIColor colorWithWhite:0.971 alpha:1.000];
    
    _moreTableView.tableHeaderView = _headerView;
//    [_headerView.collectionButton addTarget:self action:@selector(collectionButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    
    [self getCache];
//    [_headerView.setButton addTarget:self action:@selector(setButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [_headerView.removeButton setTitle:self.strOfCache forState:UIControlStateNormal];
    [_headerView.removeButton addTarget:self action:@selector(removeButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    
    _moreTableView.delegate = self;
    _moreTableView.dataSource = self;
    [self.view addSubview:_moreTableView];
    
    [_moreTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"tableViewCell0"];
    [_moreTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"tableViewCell1"];
    [_moreTableView registerClass:[MoreCustomTableViewCell class] forCellReuseIdentifier:@"tableViewCell2"];
    [_moreTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"moreTableViewCell3"];
    

}
//创建自定义提示栏
- (void)createPrompBox
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIView *customPromptBox = [UIView new];
    [window addSubview:customPromptBox];
    customPromptBox.backgroundColor = [UIColor colorWithWhite:0.216 alpha:1.000];
    customPromptBox.center = window.center;

    customPromptBox.clipsToBounds = YES;
    customPromptBox.layer.cornerRadius = 5;
    customPromptBox.layer.borderColor = [UIColor redColor].CGColor;
    [customPromptBox mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.centerY.mas_equalTo(0);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(50);
    }];
    _proLabel = [UILabel new];
    [customPromptBox addSubview:_proLabel];
    _proLabel.textAlignment = NSTextAlignmentCenter;
    _proLabel.textColor = [UIColor whiteColor];
    _proLabel.text = @"缓存已清理";
    [_proLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.mas_equalTo(0);
        make.width.mas_equalTo(customPromptBox.mas_width);
        make.height.mas_equalTo(customPromptBox.mas_height);
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        2秒后移除
        [customPromptBox removeFromSuperview];
    });

}


//清除缓存按钮的点击方法
- (void)removeButtonClicked
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示信息" message:@"是否清除缓存" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *actionSure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self clearCathe];
        [self createPrompBox];
    }];
    
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:actionSure];
    [alertController addAction:actionCancel];
    [self presentViewController:alertController animated:YES completion:nil];
    
}
//计算清除的缓存
- (void)getCache
{
    NSString *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject;
    float size = [self getSizeAtPath:path];
    self.strOfCache = [NSString stringWithFormat:@"缓存:%0.1fM",size];

    [self.moreTableView reloadData];
}

//遍历文件夹获得文件夹的大小并返回
- (float)getSizeAtPath:(NSString *)path
{
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:path]) {
        return 0;
    } else {
        NSEnumerator *chirdFilesEnumerator = [[manager subpathsAtPath:path] objectEnumerator];
        long long getSize = 0;
        NSString *fileName;
        while ((fileName = [chirdFilesEnumerator nextObject]) != nil) {
            NSString *fileAbsolutePath = [path stringByAppendingPathComponent:fileName];
            getSize += [self fileSizeAtPath:fileAbsolutePath];
        }
        return getSize / (1024.0 * 1024.0);
    }
}

//计算单个文件大小
- (long long)fileSizeAtPath:(NSString *)filePath
{
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]) {
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    } else {
        return 0;
    }
}

//清除缓存
- (void)clearCathe
{
    NSString *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject;
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:path];
    for (NSString *str in files) {
        NSError *error;
        NSString *strOfPath = [path stringByAppendingPathComponent:str];
        if ([[NSFileManager defaultManager] fileExistsAtPath:strOfPath]) {
            [[NSFileManager defaultManager] removeItemAtPath:strOfPath error:&error];
        }
    }
    
    [self getCache];
    [_headerView.removeButton setTitle:self.strOfCache forState:UIControlStateNormal];
    NSLog(@"22222222%@",self.strOfCache);
    
}

//设置按钮的点击方法
- (void)setButtonClicked
{
    SetViewController *setVC = [[SetViewController alloc] init];
    [self.navigationController pushViewController:setVC animated:YES];
}


//- (void)collectionButtonClicked
//{
//    CollectionButtonViewController *collecVC = [CollectionButtonViewController new];
//    [self.navigationController pushViewController:collecVC animated:YES];
//}

- (void)viewAppear
{
    
    [UIView animateWithDuration:0.1 animations:^{
        _moreView.fll_y = 167;
    }];
    _morebackView.backgroundColor = [UIColor blackColor];
    _morebackView.alpha = 0.4;
}

- (void)viewDisappear
{
    [UIView animateWithDuration:0.2 animations:^{
        _moreView.fll_y = 667;
        _morebackView.backgroundColor = [UIColor whiteColor];
        _morebackView.alpha = 0;
    }];
}

#pragma mark ----------moretableView返回cell的方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableViewCell0"];
        UIImageView *sectionImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH / 375 * 150)];
        [sectionImageView sd_setImageWithURL:[NSURL URLWithString:_moreESRootClass.grids[1].goodies[3].pic]];
        [cell addSubview:sectionImageView];

        return cell;
    
        } else if (indexPath.section == 1) {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableViewCell1"];
    MoreCollectionViewController *moreCollectionVC = [MoreCollectionViewController new];
    [self addChildViewController:moreCollectionVC];
    [cell addSubview:moreCollectionVC.view];

    return cell;
        
    } else if (indexPath.section == 2) {
        MoreCustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableViewCell2"];
    [cell.iconImageView sd_setImageWithURL:[NSURL URLWithString:_moreESRootClass.apps[indexPath.row].icon]];
        cell.nameLabel.text = _moreESRootClass.apps[indexPath.row].name;
        cell.descLabel.text = _moreESRootClass.apps[indexPath.row].desc;

        return cell;
    }
     else {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"moreTableViewCell3"];

    MoreMiddleViewController *middleVC = [MoreMiddleViewController new];
    [self addChildViewController:middleVC];
    [cell addSubview:middleVC.view];
    return cell;
    }

}
#pragma mark --------moretableViewcell的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 2) {
        return 4;
    }
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return SCREEN_WIDTH / 375 * 150;
    
    } else if (indexPath.section == 1) {
        return SCREEN_WIDTH / 375 * 120;
    } else if (indexPath.section == 2) {
        return SCREEN_WIDTH / 375 * 100;
    } else {
        return 1320;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

#pragma mark ------more网络请求
- (void)moreNetworkGet
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *requestURLString = @"http://watch-cdn.idailywatch.com/app/watch/honored?ver=iphone&app_ver=15&lang=zh-Hans-CN";
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = 0;
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager GET:requestURLString parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSDictionary dictionary];
        dic = responseObject;
        _moreESRootClass = [MoreESRootClass modelWithDic:dic];
        
        [self.moreTableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",task.currentRequest);
        NSLog(@"请求失败%@",error);
    }];
    
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2) {
        
        MoreDetailViewController *moreDetailVC = [MoreDetailViewController new];
        moreDetailVC.url = _moreESRootClass.apps[indexPath.row + 1].url;
        [self.navigationController pushViewController:moreDetailVC animated:YES];
    }
    if (indexPath.section == 0) {
        MoreDetailViewController *moreDetailVC = [MoreDetailViewController new];
        moreDetailVC.url = _moreESRootClass.grids[1].goodies[1].url;
        [self.navigationController pushViewController:moreDetailVC animated:YES];
    }
    
    
}








- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
